package mqtt

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"log"
)

var (
	client   mqtt.Client
	broker   = "192.168.20.31"
	port     = 1883
	clientId = "kibo-mqtt"
	userName = "kibo-iot"
	password = "kiboIot@2020"
	topics   = []string{"topic/test", "topic/test2"}
)

var messageChan = make(chan mqtt.Message, 10)

var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	// put the mqtt.Message to chan
	messageChan <- msg
}

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
	// anything can be did when connected
	log.Println("Connected")
	sub(client)
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
	// anything can be did when connect lost,If the client is squeezed out, it automatically reconnects
	log.Printf("Connect lost: %v", err)
}

func initClient() {
	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
	opts.SetClientID(clientId)
	opts.SetUsername(userName)
	opts.SetPassword(password)
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler
	client = mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		log.Panicln("failed to init mqtt client", token.Error())
	}
}

func sub(client mqtt.Client) {
	if len(topics) == 0 {
		log.Fatalf("Unspecified subject: failed to subscribe to %s : ", topics)
	}
	for _, j := range topics {
		token := client.Subscribe(j, 1, nil)
		token.Wait()
		log.Printf("%s 订阅成功", j)
	}
}

func GetMessageChan() chan mqtt.Message {
	if client == nil {
		initClient()
	} else if !client.IsConnected() {
		client.Connect()
	}
	return messageChan
}

func Push(topic, message string) {
	if client == nil {
		initClient()
	} else if !client.IsConnected() {
		client.Connect()
	}
	token := client.Publish(topic, 1, true, []byte(message))
	token.Wait()
}
